const Router = require('koa-router');
const router = new Router();
const tools = require("../../tools/tool");
const {exec} = require("child_process");

// 发送验证码
router.post('/common/sendSms', async ctx => {
    let mobile = tools.xe.toString(ctx.request.body.phone);
    // let user = await db.models['admin'].findOne({
    //     where: {
    //         username: mobile
    //     }
    // })
    // if(!user) {
    //     user = await db.models['admin'].findOne({
    //         where: {
    //             mobile: mobile
    //         }
    //     })
    //     if(!user) {
    //         return ctx.err('没有该手机号用户')
    //     }
    // }
    let command = `curl -X POST  http://smsapi.sanzhiyun.cn/1/requestSmsCode -H "X-Bmob-Application-Id:6095550591df6bd5b252fad4012dcc90" -H "X-Bmob-REST-API-Key: 83e5bbe060ffd6d7e346919df019edb5" -d "{\\"mobilePhoneNumber\\": \\"${mobile}\\"}" -H "Content-Type: application/json"`
    let ret = await exeCurl(command)
    if(ret.stat) {
        return ctx.suc('验证码已发送',ret.data)
    }
    else {
        return ctx.err(ret.msg)
    }
})




const exeCurl = (command) => {
    return new Promise(async (resolve) => {
        exec(command,  (error, stdout) => {
            let obj = JSON.parse(stdout)
            if(obj.error) {
                resolve({stat: false, msg: obj.error, data: ''})
            }
            if (error !== null) {
                resolve({stat: false, msg: '发送失败', data: ''})
            }
            if (obj.smsId) {
                resolve({stat: true, msg: '', data: obj.smsId})
            } else {
                resolve({stat: false, msg: '发送失败', data: ''})
            }
        })
    })
}






module.exports = router;